import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_base_lib/flutter_base_lib.dart';
class LogInterceptors extends InterceptorsWrapper {
  final String _tag = 'HttpLog';

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    M7Log.i(tag: _tag, msg: "****************onRequest() start*******************");
    M7Log.i(tag: _tag, msg: 'url：${_getUrl(options)}');
    M7Log.i(tag: _tag, msg: 'headers: ${json.encode(options.headers)}');
    M7Log.i(tag: _tag, msg: 'method: ${options.method}');
    M7Log.i(tag: _tag, msg: 'responseType: ${options.responseType.toString()}');
    M7Log.i(tag: _tag, msg: 'followRedirects: ${options.followRedirects}');
    M7Log.i(tag: _tag, msg: 'connectTimeout: ${options.connectTimeout}');
    M7Log.i(tag: _tag, msg: 'receiveTimeout: ${options.receiveTimeout}');
    M7Log.i(tag: _tag, msg: 'extra: ${json.encode(options.extra)}');
    M7Log.i(tag: _tag, msg: 'queryParameters: ${json.encode(options.queryParameters)}');
    M7Log.i(tag: _tag, msg: 'params: ${json.encode(options.data ?? {})}');
    M7Log.i(tag: _tag, msg: "****************onRequest() end*********************");
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    M7Log.i(tag: _tag, msg: "****************onResponse() start******************");
    _printResponse(response);
    M7Log.i(tag: _tag, msg: "****************onResponse() end********************");
    super.onResponse(response, handler);
  }

  void _printResponse(Response response) {
    M7Log.i(tag: _tag, msg: 'url: ${_getUrl(response.requestOptions)}');
    M7Log.i(tag: _tag, msg: 'statusCode: ${response.statusCode}');
    if (response.isRedirect == true) {
      M7Log.i(tag: _tag, msg: 'redirect: ${response.realUri}');
    }
    M7Log.i(tag: _tag, msg: 'response headers: ${response.headers.toString()}');
    M7Log.i(tag: _tag, msg: 'Response Text: ${response.toString()}');
  }

  String _getUrl(RequestOptions requestOptions) {
    String path = requestOptions.path;
    if (!path.startsWith(Constants.httpStartWith)) {
      return requestOptions.baseUrl + path;
    } else {
      return path;
    }
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    M7Log.e(tag: _tag, msg: "****************onError() start*********************");
    M7Log.e(tag: _tag, msg: '请求异常: ${err.toString()}');
    M7Log.e(tag: _tag, msg: '请求异常信息: ${err.response?.toString()}');
    M7Log.e(tag: _tag, msg: "****************onError() end***********************");
    super.onError(err, handler);
  }
}
